package com.lwl.office.webeditor.parser;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.lwl.office.webeditor.ParserContext;
import com.lwl.office.webeditor.style.Style;
import com.lwl.office.webeditor.tools.ConvertUtil;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFPicture;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.jsoup.nodes.Element;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.IOException;


public class ImageNodeParser extends NodeParser {
    @Override
    public void parser(ParserContext context, Style style) {
        Element node = (Element) getNode();
        //<img src="" width="122" height="121" border="1" alt="百度logo" vspace="2"/>
        String src = node.attr("src");
        String width = node.attr("width");
        String height = node.attr("height");
        String border = node.attr("border");
        String alt = node.attr("alt");
        //边距
        String vspace = node.attr("vspace");
        HttpResponse response = HttpUtil.createGet(src).execute();
        XWPFParagraph paragraph = context.getParagraph();
        XWPFRun run = paragraph.createRun();
        try {
            byte[] bytes = response.bodyBytes();
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
            BufferedImage image = ImageIO.read(byteArrayInputStream);
            int w = StrUtil.isEmpty(width)?image.getWidth(): ConvertUtil.toWordImageLen(width);
            int h = StrUtil.isEmpty(height)?image.getHeight():ConvertUtil.toWordImageLen(height);
            XWPFPicture picture = run.addPicture(new ByteArrayInputStream(bytes), image.getType(), alt, Units.toEMU(w),Units.toEMU(h));
            //TODO 图片样式渲染
        } catch (InvalidFormatException | IOException e) {
            e.printStackTrace();
        }

    }
}
